package com.mrx.commons.aop;

import com.mrx.commons.annotations.IgnoreLog;
import com.mrx.commons.annotations.XLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author Mr.X
 * @since 2023-01-14 11:42
 */
@Aspect
@Component
public class AOPLog {

    private static final Logger logger = LoggerFactory.getLogger(AOPLog.class);

    @Pointcut("@within(com.mrx.commons.annotations.XLog) || @within(com.mrx.commons.annotations.XLogService)")
    public void log() {
    }

    @Around("log()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        String method = signature.getName();
        Class<?> targetClass = pjp.getTarget().getClass();
        // 只有 XLog 有这个参数, XLogService 没有
        if (targetClass.isAnnotationPresent(XLog.class)) {
            String[] ignoreMethod = targetClass.getAnnotation(XLog.class).ignoreMethod();
            // 执行 ignoreMethod 中的方法 或 方法带有 IgnoreLog 注解 时不输出日志
            if (Arrays.asList(ignoreMethod).contains(method) || signature.getMethod().isAnnotationPresent(IgnoreLog.class)) {
                return pjp.proceed();
            }
        }
        logger.debug("准备执行: {}.{}(), 参数: {}", signature.getDeclaringType().getName(), method, pjp.getArgs());
        long start = System.currentTimeMillis();
        Object proceed = pjp.proceed();
        Object logRes = proceed;
        if (proceed instanceof byte[])
            logRes = "byte[" + ((byte[]) proceed).length + "]";
        logger.debug("{} 执行完毕, 花费 {} ms, 返回值为: {}", method, System.currentTimeMillis() - start, logRes);
        return proceed;
    }

}
